package com.qf.web.controller;

import cn.dsna.util.images.ValidateCode;
import com.qf.domain.Address;
import com.qf.domain.User;
import com.qf.service.AddressService;
import com.qf.service.UserService;
import com.qf.service.impl.AddressServiceImpl;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.Base64Utils;
import com.qf.utils.RandomUtil;
import com.qf.utils.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;

/**
 * projectName:myxiaomi
 * author:LiPengChong
 * time:2024/4/15 14:22
 * description:
 */
@WebServlet("/userservlet")
public class UserServlet extends BaseServlet {
    //【注册】
    public String register(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String repassword = request.getParameter("repassword");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");
        //非空校验
        if (StringUtils.isEmpty(username)) {
            request.setAttribute("msg", "用户名不能为空");
            return "/register.jsp";//通过继承BaseServlet，调用BaseServlet里面的doGet,doPost方法，然后进行转发
        }
        if (StringUtils.isEmpty(password)) {
            request.setAttribute("msg", "密码不能为空");
            return "/register.jsp";
        }
        if (!password.equalsIgnoreCase(repassword)) {//equalsIgnoreCase忽略大小写
            request.setAttribute("msg", "两次密码不一致");
            return "/register.jsp";
        }
        if (StringUtils.isEmpty(email)) {
            request.setAttribute("msg", "邮箱不能为空");
            return "/register.jsp";
        }

        //调用业务逻辑
        UserService userService = new UserServiceImpl();
        boolean b = userService.checkUserName(username);//查询用户名是否存在
        if (b) { //为true 证明用户名已存在
            request.setAttribute("msg", "用户名已存在");
            return "/register.jsp";
        }
        User user = new User(0, username, password, email, gender, 0, 1, RandomUtil.createActiveCode());
        try {
            userService.register(user);
            //转发重定向
            return "redirect:/registerSuccess.jsp";//重定向
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "注册失败");
            return "/register.jsp";
        }
    }

    //【登录】
    public String login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String vcode = request.getParameter("vcode");

        //后加  auto自动登录
        String auto = request.getParameter("auto");

        //非空校验
        if (StringUtils.isEmpty(username)) {
            request.setAttribute("msg", "用户名不能为空");
            return "/message.jsp";//通过继承BaseServlet，调用BaseServlet里面的doGet,doPost方法，然后进行转发
        }
        if (StringUtils.isEmpty(password)) {
            request.setAttribute("msg", "密码不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(vcode)) {
            request.setAttribute("msg", "验证码不能为空");
            return "/message.jsp";
        }
        //校验验证码
        String code = (String) request.getSession().getAttribute("vcode");
        if (!vcode.equalsIgnoreCase(code)) {//equalsIgnoreCase忽略大小写
            request.setAttribute("msg", "验证码输入错误");
            return "/message.jsp";
        }
        try {
            //2.调用业务逻辑
            UserService userService = new UserServiceImpl();
            User user = userService.login(username, password);
            //把用户存入session
            request.getSession().setAttribute("user", user);

            //后加【自动登录】
            System.out.println(auto);//自动登录勾选是on 不勾选是null
            if (auto != null) {
                //不为mull，完成自动登录
                String userInfo = username + "#" + password;
                //Base64处理
                userInfo = Base64Utils.encode(userInfo);
                Cookie cookie = new Cookie("userInfo", userInfo);
                //设置路径
                cookie.setPath(request.getContextPath());
                //有效日期
                cookie.setMaxAge(14 * 24 * 60 * 60);//设置两周自动登录
                //设置
                cookie.setHttpOnly(true);
                //回写
                response.addCookie(cookie);
            }
            //转发重定向
            return "redirect:/index.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "用户登录失败：" + e.getMessage());
            return "/message.jsp";
        }
    }

    //【获取验证码功能】
    public String code(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //清除缓存
        response.setHeader("Pragma", "no-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", -1);
        //创建验证码对象
        ValidateCode validateCode = new ValidateCode(100, 28, 4, 20);
        //把验证码存入session中
        request.getSession().setAttribute("vcode", validateCode.getCode());
        System.out.println(validateCode.getCode());
        //响应给浏览器
        validateCode.write(response.getOutputStream());
        return null;
    }


    /**
     * 验证用户名是否存在
     *
     * @param request
     * @param response
     * @return
     * @throws ServletException
     * @throws IOException
     */
    //【检查用户名】
    public String checkUserName(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String username = request.getParameter("username");
        System.out.println("username=" + username);
        if (StringUtils.isEmpty(username)) {
            response.getWriter().write("1");//1证明不可用
        }
        //调用业务逻辑
        UserService userService = new UserServiceImpl();
        Boolean b = userService.checkUserName(username);
        if (b) {//b=true 证明找到了用户，用户已存在不可用
            response.getWriter().write("1");
            return null;//return null;证明既不转发也不重定向
        }
        response.getWriter().write("0");//否则用户不存在，返回0，可以用
        return null;
    }


    //【退出】logOut
    public String logOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.移除session中的信息
        HttpSession session = request.getSession();
        session.removeAttribute("user");
        //2.session失效
        session.invalidate();
        //3.删除自动登录的cookie
        Cookie cookie = new Cookie("userInfo", "");
        //设置路径
        cookie.setPath(request.getContextPath());
        //有效日期
        cookie.setMaxAge(0);
        response.addCookie(cookie);//向客户端发送新的cookie
        //4.重定向
        return "redirect:/index.jsp";
    }



    /*----------------------------------地址模块(上面的都是用户模块)-------------------------------------------------------------*/

    //【新增地址】
    //http://localhost:8080/userservlet?method=addAddress
    public String addAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.判断用户是否的登录
        User user = (User) request.getSession().getAttribute("user");//获取session域中的session对象
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //2.获取前端数据
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");//detail:详情
        //3.非空验证
        if (StringUtils.isEmpty(name)) {
            request.setAttribute("msg", "收件人姓名不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(phone)) {
            request.setAttribute("msg", "收件人电话不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(detail)) {
            request.setAttribute("msg", "收件人地址不能为空");
            return "/message.jsp";
        }
        try {
            //4.调用业务逻辑
            AddressService addressService = new AddressServiceImpl();
            Address address = new Address(0, detail, name, phone, user.getId(), 0);
            addressService.add(address);
            return "redirect:/userservlet?method=getAddress";//新增之后在再查一遍
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "收件人地址不能为空" + e.getMessage());
            return "/message.jsp";
        }
    }


    //【查询地址】
    //userservlet?method=getAddress
    public String getAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.判断用户是否的登录
        User user = (User) request.getSession().getAttribute("user");//获取session域中的session对象
        if (user == null) {
            return "redirect:/login.jsp";
        }
        try {
            //2.调用业务逻辑
            AddressService addressService = new AddressServiceImpl();
            List<Address> addList = addressService.find(user.getId());
            //存值
            request.setAttribute("addList", addList);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "查询地址失败" + e.getMessage());
            return "/message.jsp";
        }
        return "/address_info.jsp";
    }


    //【删除地址功能】
    //http://localhost:8080/userservlet?method=deleteAddress&id=10
    public String deleteAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.判断用户是否的登录
        User user = (User) request.getSession().getAttribute("user");//获取session域中的session对象
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //2.获取前端数据
        String id = request.getParameter("id");
        //非空验证
        if (StringUtils.isEmpty(id)) {
            request.setAttribute("msg", "id不能为空");
            return "/message.jsp";
        }
        try {
            //3.调用业务逻辑
            AddressService addressService = new AddressServiceImpl();
            addressService.remove(user.getId(), Integer.parseInt(id));//通过用户uid 和地址对应的id进行地址的删除
            return "redirect:/userservlet?method=getAddress";//删除之后在再查一遍，重定向到getAddress
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "删除地址失败" + e.getMessage());
            return "/message.jsp";
        }
    }

    //【设置默认地址】
    //http://localhost:8080/userservlet?method=defaultAddress&id=7
    public String defaultAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.判断用户是否的登录
        User user = (User) request.getSession().getAttribute("user");//获取session域中的session对象
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //2.获取前端数据
        String id = request.getParameter("id");
        //非空验证
        if (StringUtils.isEmpty(id)) {
            request.setAttribute("msg", "id不能为空");
            return "/message.jsp";
        }
        try {
            //3.调用业务逻辑
            AddressService addressService = new AddressServiceImpl();
            addressService.updateLevel(user.getId(), Integer.parseInt(id));
            return "redirect:/userservlet?method=getAddress";//删除之后在再查一遍，重定向到getAddress
        } catch (NumberFormatException e) {
            e.printStackTrace();
            request.setAttribute("msg", "设置默认地址失败" + e.getMessage());
            return "/message.jsp";
        }
    }


    //【地址信息修改】
    //http://localhost:8080/userservlet?method=updateAddress
    public String updateAddress(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.判断用户是否的登录
        User user = (User) request.getSession().getAttribute("user");//获取session域中的session对象
        if (user == null) {
            return "redirect:/login.jsp";
        }
        //2.获取前端数据
        String id = request.getParameter("id");
        String level = request.getParameter("level");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        //非空验证
        if (StringUtils.isEmpty(id)) {
            request.setAttribute("msg", "地址编号不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(name)) {
            request.setAttribute("msg", "收件人姓名不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(phone)) {
            request.setAttribute("msg", "收件人电话不能为空");
            return "/message.jsp";
        }
        if (StringUtils.isEmpty(detail)) {
            request.setAttribute("msg", "收件人地址不能为空");
            return "/message.jsp";
        }
        try {
            //调用业务逻辑
            AddressService addressService = new AddressServiceImpl();
            Address address = new Address(Integer.parseInt(id), detail, name, phone, user.getId(), Integer.parseInt(level));
            addressService.update(address);
            return "redirect:/userservlet?method=getAddress";
        } catch (NumberFormatException e) {
            e.printStackTrace();
            request.setAttribute("msg", "修改地址失败" + e.getMessage());
            return "/message.jsp";
        }
    }


    /*-----------------------------------------后台管理系统登录,退出-----------------------------------------------------------*/
    //【管理员登录】
    //userservlet?method=adminLogin
    public String adminLogin(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取前端数据
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //非空校验
        if (StringUtils.isEmpty(username)) {
            request.setAttribute("msg", "用户名不能为空");
            return "/message.jsp";//通过继承BaseServlet，调用BaseServlet里面的doGet,doPost方法，然后进行转发
        }
        if (StringUtils.isEmpty(password)) {
            request.setAttribute("msg", "管理员密码不能为空");
            return "/message.jsp";
        }
        try {
            //2.调用业务逻辑
            UserService userService = new UserServiceImpl();
            User admin = userService.adminLogin(username, password);
            request.getSession().setAttribute("admin", admin);

            return "redirect:/admin/admin.jsp";
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "登录失败" + e.getMessage());
            return "/message.jsp";
        }
    }

    //【管理员退出】
    //http://localhost:8080/admin/userservlet?method=adminLoginOut
    public String adminLoginOut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println(111);
        //1.移除session中的信息
        HttpSession session = request.getSession();
        session.removeAttribute("admin");
        //2.session失效
        session.invalidate();
        //创建新的cookie
        Cookie cookie = new Cookie("adminCookie","");
        //设置路径
        cookie.setPath(request.getContextPath());//确保只有与当前 Web 应用相同路径的页面才能访问该 Cookie。(返回了当前 Web 应用的上下文路径，通常是应用的根路径)
        //设置有效日期
        cookie.setMaxAge(0);
        //向客户端发送新的cookie
        response.addCookie(cookie);

        return "redirect:/admin/login.jsp";
    }
}